package com.hopu.shiro_demo;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义Realm
 */
public class MyRealm extends AuthorizingRealm {
    /**
     * 返回授权信息，用户登录后具有哪些角色和权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获得登录成功的用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("当前的用户是：" + username);
        //创建授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        roles.add("user");
        roles.add("admin");
        info.setRoles(roles);                   //授权用户的角色
        Set<String> permissions = new HashSet<>();
        permissions.add("select-goods");
        permissions.add("insert-goods");
//        permissions.add("update-goods");
        permissions.add("delete-goods");
        info.setStringPermissions(permissions); //授权用户具有的权限
        return info;
    }

    /**
     * 返回验证信息，指定用户进行登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获得用户输入的账号和密码
        String username = authenticationToken.getPrincipal().toString();
        String password = authenticationToken.getCredentials().toString();
        System.out.println("用户填写的账号和密码："+username+"--"+password);
        //进行用户名验证
        if(!"zhangsan".equals(username)){
            throw new UnknownAccountException("用户名不存在");
        }
        //返回验证信息，包含正确的账号和密码，由Shiro框架进行验证
        //四个参数：1）账户名 2）密码 3）盐 4）realm的名称
        return new SimpleAuthenticationInfo("zhangsan","123456",null,getName());
    }
}
